package com.example.wxtest.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.wxtest.util.Configure;
import com.example.wxtest.util.SignUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

/**
 * @version 1.0
 * @description:
 * @author: lvyq
 * @date: 2022/7/8 15:16
 */

@RequestMapping
@RestController
@CrossOrigin
public class WXtestController {
    @Autowired
    SignUtil signUtil;

    //    公众号html页面获取微信用户信息
    @GetMapping("/getUserInfo")
    public String getAccessToken(@RequestParam("code") String code) {
        //网页获取用户信息，获取accessToken
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + Configure.appId + "&secret=" + Configure.appsecret + "&code=" + code + "&grant_type=authorization_code";
        // 发送请求
        String accessTokenBody = cn.hutool.http.HttpUtil.get(url);
        com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(accessTokenBody);
        String accessToken = null;
        String openId = null;
        try {
            accessToken = (String) jsonObject.get("access_token");
            openId = (String) jsonObject.get("openid");
        } catch (Exception e) {
            System.out.println(e);
        }
        System.out.println("accessToken+'*'+openId====");
        System.out.println(accessToken + '*' + openId);
//        获取用户信息
        String getInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openId + "&lang=zh_CN";
        String infoBody = cn.hutool.http.HttpUtil.get(getInfoUrl);
        com.alibaba.fastjson.JSONObject infoJsonObject = com.alibaba.fastjson.JSONObject.parseObject(infoBody);

        return infoJsonObject.toJSONString();
    }

    public static final String Token = "123456"; //微信公众平台中设置的token

    //获取js-sdk  wx.config
    @GetMapping("/getWxConfig")
    public JSONObject getWxConfig(String url) throws NoSuchAlgorithmException {
        System.out.println("获取微信config======================");
        System.out.println(url);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("debug", false);
        jsonObject.put("appId", Configure.appId);
        Long st = System.currentTimeMillis() / 1000;
        jsonObject.put("timestamp", st);
        jsonObject.put("nonceStr", "wx-js-sdk");
        String[] arr = {"startRecord", "stopRecord", "scanQRCode",
                "uploadVoice", "downloadVoice", "translateVoice",
                "pauseVoice", "playVoice"};
        jsonObject.put("jsApiList", arr);
//        获取并生成signature
        String jsapiTicket = signUtil.getTicket(signUtil.getAccessToken());
        StringBuffer orgSha1 = new StringBuffer();
        orgSha1.append("jsapi_ticket=" + jsapiTicket);
        orgSha1.append("&noncestr=wx-js-sdk");
        orgSha1.append("&timestamp=" + st);
        orgSha1.append("&url=" + url);

        jsonObject.put("signature", SignUtil.sha1(orgSha1.toString()));
        System.out.println("微信config==========================");
        System.out.println(jsonObject.toJSONString());
        return jsonObject;
    }

    //    微信验证服务器可用性
    @RequestMapping("/")
    public void index(HttpServletResponse response, HttpServletRequest request) throws Exception {
        System.out.println("===================");
        System.out.println("验证token");
        String method = request.getMethod();
        //签名验证是get请求
        if ("GET".equals(method)) {
            // 微信加密签名
            String signature = request.getParameter("signature");
            // 随机字符串
            String echostr = request.getParameter("echostr");
            // 时间戳
            String timestamp = request.getParameter("timestamp");
            // 随机数
            String nonce = request.getParameter("nonce");
            String[] str = {Token, timestamp, nonce};
            // 字典排序
            Arrays.sort(str);
            String bigStr = str[0] + str[1] + str[2];
            // SHA1加密
            String digest = SignUtil.sha1(bigStr);
            // 确认请求来至微信
            if (digest.equals(signature)) {
                response.getWriter().print(echostr);
            }
        }
    }

//    MP_verify_BhjcOkw9IqcuKXsB.txt@
    @GetMapping("/MP_verify_BhjcOkw9IqcuKXsB.txt")
    public String text(){
        return "ok";
    }

}